package com.vcredit.bird.service.mobile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.bird.enumtype.MobileStatusEnum;
import com.vcredit.bird.service.base.BirdResponse;
import com.vcredit.bird.service.base.BirdService;
import com.vcredit.bird.vo.mobile.MobileCallHistory;
import com.vcredit.bird.vo.mobile.MobileVarible;
import com.vcredit.creditcat.exception.BirdRequestException;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.JacksonUtil;

@Service
public class MobileProcessService extends BirdService {

	@Value("${mobile.bill.init}")
	private String MOBILE_BILL_INIT; // 手机采集初始化地址

	@Value("${mobile.bill.login}")
	private String MOBILE_BILL_LOGIN; // 手机登陆地址

	@Value("${mobile.bill.sendsms}")
	private String MOBILE_SEND_SMS; // 短信发送地址

	@Value("${mobile.bill.checksms}")
	private String MOBILE_CHECK_SMS; // 验证短信地址

	@Value("${mobile.bill.crawler}")
	private String MOBILE_BILL_CRAWLER;

	@Value("${mobile.bill.query}")
	private String MOBILE_QUERY_URL;
	
	@Value("${mobile.bill.callhistory}")
	private String MOBILE_CALLBILL_URL;

	private static final String BUSID = "0";// 业务ID

	/**
	 * 手机初始化
	 * 
	 * @param name
	 * @param mobile
	 * @param identityCard
	 * @param bustype
	 * @return
	 * @throws Exception
	 */
	@Log
	public BirdResponse moblieInit(String name, String mobile, String identityCard, String bustype) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("Name", name);
		map.put("Mobile", mobile);
		map.put("IdentityCard", identityCard);
		map.put("bustype", bustype);
		map.put("busid", BUSID);
		return super.postBirdData(MOBILE_BILL_INIT, JacksonUtil.Obj2Json(map));

	}

	/**
	 * 手机登陆
	 * 
	 * @param token
	 * @param name
	 * @param mobile
	 * @param identityCard
	 * @param password
	 * @param vercode
	 * @param smsCode
	 * @param bustype
	 * @param nextCode
	 * @param webSite
	 * @return
	 * @throws Exception
	 */
	@Log
	public BirdResponse mobileLogin(String token, String name, String mobile, String identityCard, String password,
			String vercode, String smsCode, String bustype, String nextCode, String webSite) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("token", token);
		map.put("mobile", mobile);
		map.put("password", password);
		map.put("vercode", vercode);
		if (nextCode.equals("3")) {
			map.put("smscode", smsCode);
		}
		map.put("Name", name);
		map.put("IdentityCard", identityCard);
		map.put("Website", webSite);
		map.put("bustype", bustype);
		map.put("busid", BUSID);
		return super.postBirdData(MOBILE_BILL_LOGIN, JacksonUtil.Obj2Json(map), 120);
	}

	/**
	 * 发送手机验证吗
	 * 
	 * @param token
	 * @param mobile
	 * @param bustype
	 * @param webSite
	 * @return
	 * @throws Exception
	 */
	@Log
	public BirdResponse mobileSendSms(String token, String mobile, String bustype, String webSite) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("token", token);
		map.put("mobile", mobile);
		map.put("Website", webSite);
		map.put("bustype", bustype);
		map.put("busid", BUSID);
		return super.postBirdData(MOBILE_SEND_SMS, JacksonUtil.Obj2Json(map));
	}

	/**
	 * 验证手机验证码
	 * 
	 * @param token
	 * @param mobile
	 * @param vercode
	 * @param smsCode
	 * @param queryCode
	 * @param bustype
	 * @param nextCode
	 * @param webSite
	 * @return
	 * @throws Exception
	 */
	@Log
	public BirdResponse mobileCheckSms(String token, String mobile, String vercode, String smsCode, String queryCode,
			String bustype, String nextCode, String webSite) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("token", token);
		map.put("mobile", mobile);
		if (nextCode.equals("4")) {
			map.put("smscode", smsCode);
		} else if (nextCode.equals("6")) {
			map.put("querycode", queryCode);
		}
		map.put("Website", webSite);
		map.put("vercode", vercode);
		map.put("bustype", bustype);
		map.put("busid", BUSID);
		return super.postBirdData(MOBILE_CHECK_SMS, JacksonUtil.Obj2Json(map), 120);
	}

	/**
	 * 获取手机的采集状态
	 * 
	 * @param mobileId
	 * @param bustype
	 * @return
	 * @throws Exception
	 */
	@Log
	public BirdResponse mobileCrawlerState(String mobileId, String bustype) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", mobileId);
		map.put("bustype", bustype);
		map.put("busid", BUSID);
		return super.postBirdData(MOBILE_BILL_CRAWLER, JacksonUtil.Obj2Json(map));
	}

	@Log
	public MobileVarible mobileVaible(String mobileId) throws Exception {
		String param = "{\"id\":\"" + mobileId + "\"}";
		BirdResponse response = postBirdData(MOBILE_QUERY_URL, param);
		try {
			return JacksonUtil.Json2Obj(response.getResult(), new TypeReference<MobileVarible>() {
			});
		} catch (IOException e) {
			e.printStackTrace();
			throw new BirdRequestException(e.getMessage());
		}
	}

	/**
	 * 判断是否实名
	 * 
	 * @param realName
	 * @param realIdNo
	 * @param mobileVarible
	 * @return
	 */
	@Log
	public MobileStatusEnum isReal(String realName, String realIdNo, MobileVarible mobileVarible) {
		// 聚信立报告中已经是实名状态
		if ("1".equals(mobileVarible.getIsRealNameAuth())) {
			return MobileStatusEnum.REAL_NAME;
		}

		String checkName = mobileVarible.getName();
		String checkIdNo = mobileVarible.getIdentityCard();

		if (StringUtils.isBlank(checkIdNo) && StringUtils.isBlank(checkName)) {
			return MobileStatusEnum.NOT_REAL_NAME;
		}

		if ("未身份确认".equals(checkIdNo)) {// 特例
			checkIdNo = "";
		}
		if ("***************".equals(checkIdNo)) {// 特例
			checkIdNo = "";
		}
		if ("协议补资".equals(checkName)) {// 特例
			checkName = "";
		}
		if ("--".equals(checkName)) {// 特例
			checkName = "";
		}
		if ("预开账户".equals(checkName)) {// 特列
			checkName = "";
		}

		if (StringUtils.isBlank(checkIdNo)) {// 身份证为空
			if (StringUtils.isBlank(checkName)) {// 姓名为空
				return MobileStatusEnum.AUTHENTICATE_FAIL;
			}
			if (checkName(realName, checkName)) {// 姓名匹配
				return MobileStatusEnum.REAL_NAME;
			}
			if (!checkName(realName, checkName)) {// 姓名不匹配
				return MobileStatusEnum.NOT_REAL_NAME;
			}

		}

		if (cheakId(realIdNo, checkIdNo)) {
			if (StringUtils.isBlank(checkName)) {// 姓名为空
				return MobileStatusEnum.REAL_NAME;
			}
			if (checkName(realName, checkName)) {// 姓名匹配
				return MobileStatusEnum.REAL_NAME;
			}
			if (!checkName(realName, checkName)) {// 姓名不匹配
				return MobileStatusEnum.NOT_REAL_NAME;
			}
		}

		if (!cheakId(realIdNo, checkIdNo)) {
			if (StringUtils.isBlank(checkName)) {// 姓名为空
				return MobileStatusEnum.NOT_REAL_NAME;
			}
			if (checkName(realName, checkName)) {// 姓名匹配
				return MobileStatusEnum.NOT_REAL_NAME;
			}
			if (!checkName(realName, checkName)) {// 姓名不匹配
				return MobileStatusEnum.NOT_REAL_NAME;
			}
		}

		return MobileStatusEnum.REAL_NAME;
	}

	private boolean checkName(String realName, String mobileName) {
		String reg = "[^\u4e00-\u9fa5]";
		// 把所有字符转换成统一字符
		mobileName = mobileName.replaceAll(reg, "*");

		if (realName.length() == mobileName.length()) {// 姓名长度相同，每个汉字都核对
			for (int i = 0; i < mobileName.length(); i++) {
				if (mobileName.charAt(i) == '*') {
					continue;
				} else {
					if (mobileName.charAt(i) != realName.charAt(i)) {
						return false;
					}
				}
			}
		} else {// 姓名长度不相同，如果有 * 只核对首位和末尾的汉字 , 如果没有 * 就直接不通过
			if (mobileName.indexOf('*') == -1) {
				return false;
			}
			if (mobileName.charAt(0) != '*') {
				if (mobileName.charAt(0) != realName.charAt(0)) {
					return false;
				}
			}
			if (mobileName.charAt(mobileName.length() - 1) != '*') {
				if (mobileName.charAt(mobileName.length() - 1) != realName.charAt(realName.length() - 1)) {
					return false;
				}
			}
		}

		return true;
	}

	private boolean cheakId(String realIdNo, String checkIdNo) {
		String regID = "[^0-9]";
		// 把所有字符转换成统一字符
		if (realIdNo.length() == checkIdNo.length()) {// 身份证号长度一致
			if (checkIdNo.charAt(checkIdNo.length() - 1) == 'X' || checkIdNo.charAt(checkIdNo.length() - 1) == 'x') {
				if (realIdNo.charAt(realIdNo.length() - 1) == 'X' || realIdNo.charAt(realIdNo.length() - 1) == 'x') {
				} else {
					return false;
				}
			}
			checkIdNo = checkIdNo.replaceAll(regID, "*");
			for (int i = 0; i < checkIdNo.length() - 1; i++) {
				if (checkIdNo.charAt(i) == '*') {
					continue;
				} else {
					if (checkIdNo.charAt(i) != realIdNo.charAt(i)) {
						return false;
					}
				}
			}

		} else {// 身份证号长度不一致
			checkIdNo = checkIdNo.replaceAll(regID, "*");
			if (realIdNo.length() - checkIdNo.length() > 0) {// 填写长度大于 供应商返回的
				if (checkIdNo.indexOf("*") >= 0) {// 有特殊字符
					StringBuffer newStr = new StringBuffer(checkIdNo);
					int addCount = realIdNo.length() - checkIdNo.length();
					String insertStr = "";
					for (int i = 0; i < addCount; i++) {
						insertStr = insertStr + "*";
					}
					newStr.insert(checkIdNo.indexOf("*"), insertStr);
					for (int i = 0; i < newStr.length() - 1; i++) {
						if (newStr.charAt(i) == '*') {
							continue;
						} else {
							if (newStr.charAt(i) != realIdNo.charAt(i)) {
								return false;
							}
						}
					}
				} else {// 没有特殊字符
					return false;
				}
			} else {// 填写长度小于供应商返回的
				for (int i = 0; i < checkIdNo.length(); i++) {
					if (checkIdNo.charAt(i) == '*') {
						continue;
					} else {
						return false;
					}
				}
			}

			return true;
		}

		return true;
	}
	
	/**
	 * 根据手机爬取id查询通话详单
	 * @author zhaoqi01
	 * @param mobileId
	 * @return
	 * @throws Exception 
	 */
	@Log
	public List<MobileCallHistory> queryCalls(String mobileId) throws Exception {
		String param = "{\"id\":\"" + mobileId + "\"}";
		BirdResponse response = postBirdData(MOBILE_CALLBILL_URL, param);
		return JacksonUtil.Json2Obj(response.getResult(), new TypeReference<List<MobileCallHistory>>(){});
	}
}
